const app = Vue.createApp({
  compilerOptions: {
    delimiters: ['[[', ']]'],
  },
  data() {
    return {
      login: false,
      lock: false,
      input: "",
      data01: "linux",
      notes: [],
      content: "",
      username: "",
      // ws_url: 'ws://seadog.pythonabc.org:60558/ws/update/',
      // ws_url: 'wss://seadog.pythonabc.org:60558/noteboard/note/ws/update/',
      ws_url: 'wss://seadog.pythonabc.org:60555/noteboard/note/ws/update/',
      // ws_url: 'ws://10.222.2.203:11203/note/ws/update/',
      ws: null,
      multi_selection: false,
      select_all_mark: false,
      ws_clients: null,
      ws_clients_txt: true,
    };
  },
  methods: {
    del_multi: function () {
      // @done get confirm b4 proceed to deletion
      let IDs = []
      this.notes.forEach((item) => {
        if (item.selected) {
          IDs.push(item.id)
        }
      })
      if (IDs.length != 0) {
        let r = confirm("Confirm to delete selected notes ?");
        if (r == true) {
          axios({
            url: "/noteboard/note/delmulti/",
            method: "post",
            data: {
              "ids": IDs,
            },
          }).then((res) => {
            if (res.data.message == 'success') {
              alert('delete successfully')
            }
          }).catch((err) => {
            alert('something went wronge trying to delete selected notes!')
            this.update_notes()
          });
        }
      } else {
        alert('linux')
      }
    },
    ws_init: function () {
      let client_id = Date.now()
      var ws = new WebSocket(this.ws_url + client_id);
      ws.onerror = (event) => {
        this.ws_clients_txt = true
        this.ws_clients = "error connecting to websocket server."
      };
      ws.onclose = (event) => {
        this.ws_clients_txt = true
        this.ws_clients = "web have disconnected from the websocket server, maybe the server is offline."
      };
      ws.onmessage = (event) => {  // 这里必须用三角函数，以便将this指代vue实例
        data = event.data
        data = JSON.parse(data)
        //  @done client should info server,operation type: del,add. server will react accordingly and return proper data
        if (data['operation'] == "add") {
          this.notes.unshift(data)
        } else if (data['operation'] == "del") {
          this.notes = this.notes.filter(item => item.id != data['id'])
        } else if (data['operation'] == "client-info") {
          this.ws_clients = data.clients
        } else {
          console.log('unkonw data ')
          console.log(data)
        }
      };
      this.ws = ws
    },
    ws_sendMessage: function (message) {
      this.ws.send(message)
    },
    // @mark 这里复制到系统剪贴板的方法已过期，后期看有更合适的办法没
    copy_to_clipboard(name) {
      var el = document.getElementById(name);
      el.select();
      document.execCommand('Copy');
    },
    converter_date(date) {
      var ptn01 = new RegExp("\\d\\d\\d\\d-");
      var ptn02 = new RegExp("T");
      var ptn03 = new RegExp(":\\d\\d\\..+$");
      return date.replace(ptn01, "").replace(ptn02, " ").replace(ptn03, "");
    },
    on_del: function (id) {
      axios({
        url: "/noteboard/note/" + id,
        method: "delete",
      }).then((res) => {
        // @note 由于已经通过server端websocket广播被删除的条目，这里有点儿重复，但是最好保留，以应对websocket被内网代理屏蔽的情况
        this.notes = this.notes.filter((item) => item.id != id);
      });
    },
    on_submit: function () {
      if (this.input) {
        axios({
          url: "/noteboard/note/",
          method: "post",
          data: {
            body: this.input,
          },
        }).then((res) => {
          // this.update_notes();
          //  @done client should info server,operation type: del,add. server will react accordingly and return proper data
          //  @todo 如果ws不起效时，是否能自动调用刷新页面
          // this.ws_sendMessage(this.input)  // @note 后端通过tortoise.signals来感知数据库变动，从而无需前端发送数据
          this.input = "";
        });
      }
    },
    click_handler: function (id) {
      this.lock = true;
      this.content = this.notes.find((item) => item.id == id).body;
    },
    hover_handler: function (id) {
      if (!this.lock) {
        this.content = this.notes.find((item) => item.id == id).body;
      }
    },
    update_notes: function () {
      axios({
        url: "/noteboard/note/",
      })
        .then((res) => {
          this.notes = res.data;
          this.ws_clients_txt = false
        })
        .catch((err) => {
          // @mark 应对需登录的情况，保留这些代码
          if (err.response.status == 401) {
            this.login = true;
            this.$confirm(
              "Token expired, Please login again!",
              "",
              "error"
            ).then((res) => {
              this.$router.push({
                name: "login",
              });
            });
          } else {
            this.alert("failed to get data from backend!");
          }
        });
    },
  },
  // mounted() {
  created() {
    this.update_notes();
    this.ws_init();
  },
  watch: {
    select_all_mark: {
      handler: function () {
        this.notes.forEach((item, index, arr) => {
          arr[index]["selected"] = this.select_all_mark
        })
      }
    },
    multi_selection: {
      handler: function () {
        if (this.multi_selection == false) {
          this.notes.forEach((item, index, arr) => {
            arr[index]["selected"] = this.select_all_mark
          })
        }
      }
    }
  }
})
const vm = app.mount('#app')
